package com.sense.lib.webview.chromeclient.input;


import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.util.Log;
import android.webkit.ValueCallback;
import android.webkit.WebView;

import androidx.annotation.RequiresApi;

import com.sense.lib.webview.chromeclient.progress.ProgressChromeClient;
import com.sense.lib.webview.utils.FileProviderUtil;
import com.sense.lib.webview.utils.WebFileUtil;

import java.io.IOException;


/**
 * <br> ClassName:   TdInputLabelChromeClient
 * <br> Description: 对input标签的支持
 * <br>
 * <br> @author:      lionszhang
 * <br> Date:        2017/10/27 15:56
 */

@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public abstract class AbstractInputLabelChromeClient extends ProgressChromeClient {
    private ValueCallback<Uri[]> filePathCallback;
    private ValueCallback<Uri> uploadMsg;
    private String TAG = "InputLabelChromeClient";
    public final static int FILECHOOSER_RESULTCODE_VOICE = 1002;
    public final static int FILECHOOSER_RESULTCODE_IMAGE = 1001;
    public final static int FILECHOOSER_RESULTCODE_VIDEO = 1003;
    public final static int FILECHOOSER_RESULTCODE_DEFAULT = 1004;
    private boolean isOpenCamara = false;
    private boolean isOpenPicture = false;
    private boolean isOpenVoice = false;
    private boolean isOpenVideo = false;

    public boolean isOpenCamara() {
        return isOpenCamara;
    }

    public void setOpenCamara(boolean openCamara) {
        isOpenCamara = openCamara;
    }

    public boolean isOpenPicture() {
        return isOpenPicture;
    }

    public void setOpenPicture(boolean openPicture) {
        isOpenPicture = openPicture;
    }

    public boolean isOpenVoice() {
        return isOpenVoice;
    }

    public void setOpenVoice(boolean openVoice) {
        isOpenVoice = openVoice;
    }

    public boolean isOpenVideo() {
        return isOpenVideo;
    }

    public void setOpenVideo(boolean openVideo) {
        isOpenVideo = openVideo;
    }

    private String[] permissions = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.RECORD_AUDIO,
    };

    public AbstractInputLabelChromeClient(Activity mActivity) {
        super(mActivity);
    }

    //android 5.0 支持input标签
    @Override
    public final boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                                           FileChooserParams fileChooserParams) {
        fileChoosers(filePathCallback);
        return true;
    }

    /**
     * <br> Description: android 3.0+支持input标签
     * <br> Author:      lionszhang
     * <br> Date:        2017/10/27 16:37
     *
     * @param uploadMsg uploadMsg
     */
    public final void openFileChooser(ValueCallback<Uri> uploadMsg) {
        fileChooser(uploadMsg);
    }

    /**
     * <br> Description: android 3.0+支持input标签
     * <br> Author:      lionszhang
     * <br> Date:        2017/10/27 16:37
     *
     * @param uploadMsg  uploadMsg
     * @param acceptType acceptType
     */
    public final void openFileChooser(ValueCallback uploadMsg, String acceptType) {
        fileChooser(uploadMsg);
    }

    /**
     * <br> Description: android 4.1支持input标签
     * <br> Author:      lionszhang
     * <br> Date:        2017/10/27 16:38
     */
    public final void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
        fileChooser(uploadMsg);
    }

    /**
     * <br> Description: 打开文件选择器
     * <br> Author:      lionszhang
     * <br> Date:        2017/10/27 17:40
     *
     * @param filePathCallback 回调函数
     */
    private void fileChoosers(final ValueCallback<Uri[]> filePathCallback) {
        this.filePathCallback = filePathCallback;
        this.uploadMsg = null;
        openImageChoose();
    }

    /**
     * <br> Description: 打开文件选择器
     * <br> Author:      lionszhang
     * <br> Date:        2017/10/27 17:40
     *
     * @param uploadMsg 回调函数
     */
    private void fileChooser(final ValueCallback uploadMsg) {
        this.filePathCallback = null;
        this.uploadMsg = uploadMsg;
        openImageChoose();
    }

    /**
     * <br> Description: 打开文件选择器
     * <br> Author:      lionszhang
     * <br> Date:        2017/10/30 14:39
     */
    private void openImageChoose() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            applyPermissions(permissions, filePathCallback, uploadMsg, new ApplyPermissionsListener() {
                @Override
                public void applyResult(boolean isAgreed) {
                    open(isAgreed);
                }
            });
        } else {
            open(true);
        }
    }

    /**
     * <br> Description: 申请权限
     * <br> Author:      lionszhang
     * <br> Date:        2017/11/1 11:29
     *
     * @param permissions 权限组合
     * @param listener    回掉接口
     */

    public abstract void applyPermissions(String[] permissions, ValueCallback<Uri[]> filePathCallback,
                                          ValueCallback uploadMsg, ApplyPermissionsListener listener);

    /**
     * <br> Description: 打开相册选择
     * <br> Author:      lionszhang
     * <br> Date:        2017/11/1 11:30
     *
     * @param isAgreed 是否同意
     */
    private void open(boolean isAgreed) {
        if (!isAgreed) {
            return;
        }
        Activity mActivity = mWeakReferenceActivity.get();
        Intent intent;
        if (mActivity != null) {
            if (isOpenPicture) {
                //XIANG CHE
                Intent intentFromGallery = new Intent();
                intentFromGallery.setType("image/*");
                intentFromGallery.setAction(Intent.ACTION_PICK);


//                ZHAO XIANG JI
                Intent takePictureIntent = createCameraIntent(mActivity);

                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                intent = createChooserIntent(intentFromGallery, takePictureIntent);
                intent.putExtra(Intent.EXTRA_INTENT, i);

                mActivity.startActivityForResult(intent, FILECHOOSER_RESULTCODE_IMAGE);
            } else if (isOpenVideo) {
                intent = FileProviderUtil.createCamcorderIntent();
                mActivity.startActivityForResult(intent, FILECHOOSER_RESULTCODE_VIDEO);
            } else if (isOpenVoice) {
                intent = FileProviderUtil.createSoundRecorderIntent();
                mActivity.startActivityForResult(intent, FILECHOOSER_RESULTCODE_VOICE);
            } else {
                intent = createDefaultOpenableIntent(mActivity);
                mActivity.startActivityForResult(intent, FILECHOOSER_RESULTCODE_DEFAULT);
            }
        }

    }


    private Intent createDefaultOpenableIntent(Activity mActivity) {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("*/*");
        Intent chooser = createChooserIntent(FileProviderUtil.getTakePictureIntent(mActivity,
                WebFileUtil.INSTANCE.getFileByName(mActivity,"IMG_TAKE_PICTURE_OUT.jpg")), FileProviderUtil.createCamcorderIntent(),
                FileProviderUtil.createSoundRecorderIntent());
        chooser.putExtra(Intent.EXTRA_INTENT, i);
        return chooser;
    }

    private Intent createChooserIntent(Intent... intents) {
        Intent chooser = new Intent(Intent.ACTION_CHOOSER);
        chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents);
        chooser.putExtra(Intent.EXTRA_TITLE, "File Chooser");
        return chooser;
    }

    private Intent createCameraIntent(Activity mActivity) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Uri mPictureUri =  FileProviderUtil.getUriForFile(mActivity,WebFileUtil.INSTANCE.getFileByName(mActivity,"IMG_TAKE_PICTURE_OUT.jpg"));
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mPictureUri);
        intent.putExtra("return-data", true);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());

        mActivity.grantUriPermission(mActivity.getPackageName(), mPictureUri,
                Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(
                Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

        return intent;
    }

    private Intent createCamcorderIntent() {
        return new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
    }

    private Intent createSoundRecorderIntent() {
        return new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
    }


    private MediaRecorder recorder;  // 录音类
    private String fileName;  // 录音生成的文件存储路径

    public boolean startRecord() {
        recorder = new MediaRecorder();
        try {
            recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }

        recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
        recorder.setOutputFile("");
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        try {
            recorder.prepare();
        } catch (IOException e) {
            Log.e(TAG, "准备失败");
            e.printStackTrace();
        }
        recorder.start();
        Log.e(TAG, "开始录音...");
        return true;
    }

    public void stopRecord() {
        recorder.stop();
        recorder.reset();
        recorder.release();
        recorder = null;
        Log.e(TAG, "停止录音");
    }

    /**
     * <br> ClassName:   AbstractInputLabelChromeClient
     * <br> Description: 权限申请接口回调
     * <br>
     * <br> Author:      lionszhang
     * <br> Date:        2017/11/1 11:13
     */
    public interface ApplyPermissionsListener {
        /**
         * <br> Description: 申请权限结果回掉
         * <br> Author:      lionszhang
         * <br> Date:        2017/11/1 11:12
         *
         * @param isAgreed 是否同意权限申请
         */
        void applyResult(boolean isAgreed);
    }
}
